package com.leinao.sender;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.leinao.message.MyWebSocketMessage;
import com.leinao.session.WebSocketSessionRegister;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * webSocket 发送器
 *
 * @author zhong.wang
 * @date 2025/2/6
 */
@Slf4j
public abstract class AbstractWebSocketSender implements WebSocketSender {

    @Resource
    protected WebSocketSessionRegister sessionRegister;


    /**
     * 群发消息
     *
     * @param message
     */
    @Override
    public void send(MyWebSocketMessage message) {
        send(null,message);
    }

    /**
     * 向指定session 发送消息
     *
     * @param sessionId
     * @param message
     */
    @Override
    public void send(String sessionId, MyWebSocketMessage message) {
        List<WebSocketSession> sessions = Collections.emptyList();
        if (StrUtil.isNotEmpty(sessionId)) {
            WebSocketSession session = sessionRegister.getSessionById(sessionId);
            if (session != null) {
                sessions = Collections.singletonList(session);
            }
        }else{
            sessions = (List<WebSocketSession>) sessionRegister.getSessionList();
        }
        doSend(sessions,message);
    }

    /**
     * 发送实体
     * @param sessions
     * @param message
     */
    public void doSend(Collection<WebSocketSession> sessions, MyWebSocketMessage message) {
        String payload = JSONUtil.toJsonStr(message); // 关键，使用 JSON 序列化
        sessions.forEach(session -> {
            // 1. 各种校验，保证 Session 可以被发送
            if (session == null) {
                log.error("[doSend][session 为空, message({})]", message);
                return;
            }
            if (!session.isOpen()) {
                log.error("[doSend][session({}) 已关闭, message({})]", session.getId(), message);
                return;
            }
            // 2. 执行发送
            try {
                session.sendMessage(new TextMessage(payload));
                log.info("[doSend][session({}) 发送消息成功，message({})]", session.getId(), message);
            } catch (IOException ex) {
                log.error("[doSend][session({}) 发送消息失败，message({})]", session.getId(), message, ex);
            }
        });
    }

}
